import axios, {
  AxiosHeaders,
  AxiosError,
  type AxiosResponse,
  type InternalAxiosRequestConfig,
} from 'axios';
import type { ApiResponse } from '../api/types/apis';

axios.get('/a').then((res) => {
  res.data;
});
// 在响应拦截器中定义错误映射
const httpErrorMap: Record<number, string> = {
  400: '错误请求',
  401: '未授权，请重新登录',
  403: '拒绝访问',
  404: '请求错误，未找到资源',
  408: '请求超时',
  500: '服务器内部错误',
  501: '服务未实现',
  502: '网关错误',
  503: '服务不可用',
  504: '网关超时',
  505: 'HTTP 版本不受支持',
};

const service = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || '/api', // API 请求的默认前缀
  timeout: 5000, // 请求超时时间
});

service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    config.headers = config.headers || new AxiosHeaders();

    const token = localStorage.getItem('token');

    if (token) {
      config.headers.set('Authorization', `Bearer ${token}`);
    }

    config.params = {
      ...config.params,
      _t: Date.now(),
    };

    return config;
  },
  (error: AxiosError) => {
    console.error('请求错误:', error);
    return Promise.reject(error);
  },
);

service.interceptors.response.use(
  (response: AxiosResponse) => {
    const res = response.data;

    if (res.code !== 200) {
      console.error('请求失败:', res.message);

      switch (res.code) {
        case 401:
          console.log('未登录或 token 过期，跳转到登录页');
          break;
        case 403:
          console.log('权限不足');
          break;
        default:
          console.log('其他错误');
      }

      return Promise.reject(new Error(res.message || '请求失败'));
    }

    return res;
  },
  (error: AxiosError) => {
    const { message, response } = error;

    console.error('响应错误:', message);

    if (response) {
      const errorMessage = httpErrorMap[response.status] || `连接错误: ${response.status}`;
      console.log(errorMessage);
    } else {
      if (axios.isCancel(error)) {
        console.log('请求被取消:', message);
      } else {
        console.log('网络连接错误，请检查网络');
      }
    }

    return Promise.reject(error);
  },
);

export default service;
